package com.qianbao.components.excepion;

import com.qianbao.components.svresut.Result;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Collections;
import java.util.List;
import java.util.Map;


@ControllerAdvice
public class BadRequestExceptionHandler extends ResponseEntityExceptionHandler {


    @Override
    protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        String message = "";

        BindingResult result = ex.getBindingResult();

        if (result.hasErrors()){
            FieldError fieldError = result.getFieldError();
            message = fieldError.getDefaultMessage();
        }

        Result returnResult = Result.fail(ExceptionEnum.Request_Params_Invalid.getCode(),message, Collections.emptyMap());

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(returnResult);
    }


}
